package cn.edu.ahtcm.servlet;

import cn.edu.ahtcm.bean.User;
import cn.edu.ahtcm.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println(username);
        System.out.println(password);
       String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.2 获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
//2.3 获取Mapper
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//2.4 调用方法
        User user = userMapper.select(username, password);
//2.5 释放资源
        sqlSession.close();
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();

//3. 判断user释放为null
        if(user != null){
// 登陆成功
           req.getSession().setAttribute("user",user);
           resp.sendRedirect("/admin/manager.jsp");
        }else {
// 登陆失败
        req.getRequestDispatcher("/error.jsp").forward(req,resp);
        }
    }



    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   this.doGet(req,resp);
    }
}
